# Create your views here.
from django.http import HttpResponse
from django.shortcuts import redirect,render_to_response

import doubanoauth.oauth as oauth
import urllib,urllib2
import logging
import time

from doubancon.dconst import thekey,thesecret
from doubancon.models import Douban_Request_Token,Douban_Access_Token
from doubancon.doubanfunc import getNameById

from myuser.usercheck import getUser

from settings import URL_ROOT,SHORTCOOKIETIME,LONGCOOKIETIME

hostname = URL_ROOT
requesturl = "http://www.douban.com/service/auth/request_token"
confirmurl = "http://www.douban.com/service/auth/authorize"
accesstokenurl = "http://www.douban.com/service/auth/access_token"
confirmcallback = hostname+"/doubancon/saveauth"

signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT()
signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
signature_method = signature_method_hmac_sha1

API_HOST = 'http://api.douban.com'
AUTH_HOST = 'http://www.douban.com'
REQUEST_TOKEN_URL = AUTH_HOST+'/service/auth/request_token'
ACCESS_TOKEN_URL = AUTH_HOST+'/service/auth/access_token'
AUTHORIZATION_URL = AUTH_HOST+'/service/auth/authorize'

class MyOAuthClient:
    def __init__(self, server='www.douban.com', key=None, secret=None):
        self.server = server
        self.consumer = oauth.OAuthConsumer(key, secret)
        self.token = None

    def fetch_token(self, oauth_request):
        try:
            url1 = oauth_request.to_url()
            #return HttpResponse(url1)
            tokenurlrequest =  urllib.urlopen(url1)
            tokenstr1 = tokenurlrequest.read() 
            tokenurlrequest.close()
            #rt1 = OAuthToken.from_string(tokenstr1)
            ws = tokenstr1.split("&")
            tmpdic = {}
            for w in ws:
                kv = w.split("=")
                tmpdic[kv[0]] = kv[1]
            if tmpdic.has_key("douban_user_id"):
                return tmpdic['oauth_token'],tmpdic['oauth_token_secret'],tmpdic['douban_user_id']
            else:
                return tmpdic['oauth_token'],tmpdic['oauth_token_secret'],None
        except:
            return None,None,None

    def get_request_token(self):
        oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, 
                        http_url=REQUEST_TOKEN_URL)
        oauth_request.sign_request(signature_method, self.consumer, None)
        return self.fetch_token(oauth_request)[:2]

    def get_authorization_url(self, key, secret, callback=None):
        token = oauth.OAuthToken(key, secret)
        oauth_request = oauth.OAuthRequest.from_token_and_callback(token=token, 
                http_url=AUTHORIZATION_URL, callback=callback)
        return oauth_request.to_url()
 
    def get_access_token(self, key=None, secret=None, token=None):
        if key and secret:
            token = oauth.OAuthToken(key, secret)
        assert token is not None
        oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, 
                token=token, http_url=ACCESS_TOKEN_URL)
        oauth_request.sign_request(signature_method, self.consumer, token)
        return self.fetch_token(oauth_request)[:3]
 
    def get_auth_header(self, method, uri, parameter={}):
        if self.token:
            if not uri.startswith('http'):
                uri = API_HOST + uri
            oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, 
                    token=self.token, http_method=method, http_url=uri, parameters=parameter)
            oauth_request.sign_request(signature_method, self.consumer, self.token)
            return oauth_request.to_header()
        else:
            return {}
 
    def access_resource(self, method, url, body=None):
        oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, 
                token=self.token, http_url=url)
        oauth_request.sign_request(signature_method, self.consumer, self.token)
        headers = oauth_request.to_header()
        if method in ('POST','PUT'):
            headers['Content-Type'] = 'application/atom+xml; charset=utf-8'
        connection = httplib.HTTPConnection("%s:%d" % (self.server, 80))
        connection.request(method, url, body=body,
            headers=headers)
        return connection.getresponse()


def connect(request):
    #step1:get unauthorized token

    #return HttpResponse(thekey+thesecret)
    
    client = MyOAuthClient(key=thekey,secret=thesecret)
    key1,secret1 = client.get_request_token()

    if key1 == None:
        return HttpResponse("key is None")

    rt = Douban_Request_Token()
    rt.thekey = key1
    rt.secret = secret1
    rt.put()
    
    redirecturl = client.get_authorization_url(key1,secret1,confirmcallback)
    #redirecturl = client.get_authorization_url(key1,secret1)
    #return redirect("http://www.baidu.com")
    return redirect(redirecturl)

def saveauth(request):
    """
    if cur user login, redirect to CEU
    if cur user not login, redirect ot CNU
    """
    #step3:get access token
    oauth_token = request.GET['oauth_token']
    try:
        drt = Douban_Request_Token.all().filter('thekey =',oauth_token)[0]
    except Exception,e:
        return HttpResponse(str(e))
    #rt = oauth.OAuthToken(drt.thekey,drt.secret)
    
    #return HttpResponse("thekey:"+drt.thekey+"thesec:"+drt.secret)

    client = MyOAuthClient(key=thekey,secret=thesecret)
    key,secret,uid = client.get_access_token(drt.thekey,drt.secret)

    #here first should get the nick name instead of the uid
    #here are the problem 
    #need to check is already connected
    #if is connected,simple update the accesstoken
    #here the douban id is unique
    curuser = getUser(request)
    if Douban_Access_Token.all().filter("doubanid = ",uid).filter("userref !=",None).count() !=0:
        dat = Douban_Access_Token.all().filter("doubanid = ",uid)[0]
        if dat.userref != None:
            dic ={}
            #if same with current user or no current user
            if dat.userref == curuser or curuser == None:
                dic['theurl'] = URL_ROOT
                dic['thedesp'] = "login with douban success"
                hr = render_to_response("tools/redirect.html",dic)
                #hr.set_cookie("username",curuser.nickname,LONGCOOKIETIME)
                hr.set_cookie("key",dat.userref.key(),LONGCOOKIETIME)
                hr.set_cookie("pwd",dat.userref.pwd,LONGCOOKIETIME)
                return hr
            elif dat.userref != None:
                dic['theurl']= URL_ROOT+"/basicuser/connectstatus"
                dic['thedesp'] = "this douban account is alread linked to another"
                hr =  render_to_response("tools/redirect.html",dic)
                hr.set_cookie("key",dat.userref.key(),LONGCOOKIETIME)
                hr.set_cookie("pwd",dat.userref.pwd,LONGCOOKIETIME)
                return hr

    #check by the doubanid,if exist simple update the access token
    dcount = Douban_Access_Token.all().filter("doubanid = ",uid).count() 
    doubanname = getNameById(uid)
    if dcount == 0:
        #this douban has not connect any uid
        at = Douban_Access_Token()
        at.thekey = key
        at.secret = secret
        at.doubanid = uid
        at.doubanname = doubanname
        at.put()
    elif dcount == 1:
        d = Douban_Access_Token.all().filter("doubanid = ",uid)[0]
        d.thekey = key
        d.secret = secret
        d.put()
    else:
        raise Exception("a doauban id coresponse to more item")

    
    dic = {}
    dic['username'] = doubanname
    dic['doubanid'] = uid
    dic['doubanaccesstoken'] =key
    hr = render_to_response('myuser/conExistUser.html',dic)
    return hr
